#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
from subprocess import Popen, PIPE
LOG = open('/tmp/log_dhcpd.txt', 'a+')


def dhcpd_conf(ipprefix):
    cfgfile = '/home/love/dhcpd.conf'
    ## maybe in /etc/apparmor.d/usr.sbin.dhcpd add:
    ## /home/love/dhcpd{,6}conf r,
    ## OR put config file at the default path /etc/dhcp/*
    ##cfgfile = '/etc/dhcp/dhcpd.conf'
    cfgcontent = ('default-lease-time 300;\n'
                  'max-lease-time 360;\n'
                  'ddns-update-style none;\n'
                  'authoritative;\n'
                  'log-facility local7;\n'
                  'subnet %s netmask %s {\n'
                  '    range %s;\n'
                  '    option routers %s;\n'
                  '    option domain-name-servers %s;\n'
                  '}\n')
    dhcpconf = open(cfgfile, 'w')
    ##with open(cfgfile, 'w') as dhcpconf:
    if ipprefix == '192':
        dhcpconf.write(cfgcontent % ('192.168.0.0',
                                     '255.255.255.0',
                                     '192.168.0.2 192.168.0.100',
                                     '192.168.0.1', '233.6.6.6'))
    elif ipprefix == '172':
        dhcpconf.write(cfgcontent % ('172.16.0.0',
                                     '255.255.0.0',
                                     '172.16.0.2 172.16.0.100',
                                     '172.16.0.1', '233.6.6.6'))
    elif ipprefix == '10':
        dhcpconf.write(cfgcontent % ('10.0.0.0',
                                     '255.0.0.0',
                                     '10.0.0.2 10.0.0.100',
                                     '10.0.0.1', '233.5.5.5'))
    dhcpconf.close()
    return cfgfile

def dhcpd(dhcpdconf, ipprefix, ifcname):
    dhcpdpid = '/var/run/dhcpd.pid'
    if os.path.exists(dhcpdpid):
        pid = open(dhcpdpid).read()
        os.system('kill -9 %s' % pid)
        os.system('rm -f /var/run/dhcpd.pid')
    os.popen('echo > /var/lib/dhcp/dhcpd.leases')
    # runinfo = Popen(['dhcpd','-4','-pf /var/run/dhcpd.pid', '-q','-cf',
    #                  dhcpdconf, ifcname], stdout=PIPE, stderr=LOG)
    runinfo = Popen(['dhcpd', '-4', '-q', '-pf', dhcpdpid, '-cf', dhcpdconf, ifcname], stdout=PIPE, stderr=LOG)
    ##resu = runinfo.communicate()
    return runinfo
    # if ipprefix == '192':
    #     os.system('route add -net 192.168.0.0 netmask 255.255.255.0 gw 192.168.0.1')
    # elif ipprefix == '172':
    #     os.system('route add -net 172.16.0.0 netmask 255.255.0.0 gw 172.16.0.1')
    # elif ipprefix == '10':
    #     os.system('route add -net 10.0.0.0 netmask 255.0.0.0 gw 10.0.0.1')


if __name__ == "__main__":
    if len(sys.argv) > 2:
        file1 = dhcpd_conf(sys.argv[1])
        resu = dhcpd(file1, sys.argv[1], sys.argv[2])
        print resu.communicate()
